package cn.ulyer.core.modules.system.rest;


import cn.ulyer.common.annotation.Log;
import cn.ulyer.common.constants.ResultCode;
import cn.ulyer.common.constants.StatusEnum;
import cn.ulyer.common.jpa.entity.Dept;
import cn.ulyer.common.jpa.entity.QDept;
import cn.ulyer.common.utils.Result;
import cn.ulyer.common.utils.TreeUtil;
import cn.ulyer.core.modules.system.service.TDeptService;
import cn.ulyer.core.modules.system.vo.DeptVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * by generator - rest
 */
@RestController
@RequestMapping("/tDeptRest")
public class TDeptRest {

    private static final String MODULE = "dept" ;

    @Autowired
    private TDeptService tDeptService;


    @GetMapping("/treeDept")
    public Result<List<DeptVo>> tree(Dept dept){
        return Result.ok().data(TreeUtil.recursionCreateArrayNotRoot(tDeptService.listDeptVo(dept)));
    }

    @GetMapping("/get")
    public Result<Dept> detail(@RequestParam Long id){
        return Result.ok().data(tDeptService.getOne(id));
    }

    @PostMapping("/create")
    @Log(module = MODULE,action = Log.ActionName.CREATE)
    public Result<Long> create(@RequestBody Dept tDept){
        QDept qDept = QDept.dept;
        long queryDept = tDeptService.count(qDept.name.eq(tDept.getName()).and(qDept.status.eq(StatusEnum.ENABLE.status())));
        if(queryDept>0){
            return Result.fail("已存在同名部门");
        }
        if(tDept.getParentId()==null){
            tDept.setParentId(0L);
        }
        tDeptService.save(tDept);
        return Result.ok(ResultCode.CREATE).data(tDept.getId());
    }


    @PutMapping("/update")
    @Log(module = MODULE,action = Log.ActionName.UPDATE)
    public Result update(@RequestBody Dept tDept){
        if(tDept.getParentId()==null){
            tDept.setParentId(0L);
        }
        tDeptService.updateById(tDept);
        return Result.ok(ResultCode.UPDATE);
    }

    /**
     * removeById
     *
     */
    @DeleteMapping("/remove")
    @Log(module = MODULE,action = Log.ActionName.DELETE)
    public Result remove(@RequestParam Long id){
        tDeptService.deleteById(id);
        return Result.ok(ResultCode.DELETE);
    }



}
